<?php

/**
 * 角色分组
 * @author user
 *
 */
class RolesController extends AdminController
{
    public function indexAction()
    {
        $action = $this->get('do');
        switch ($action) {
            case 'list':
                $this->operation_log('查看角色列表');
                $parameters['conditions'] = array();
                $data = $this->_list(AdminGroupsModel::class, $parameters);
                // 翻页
                $data_result = [];
                foreach ($data['data'] as $item) {
                    $data_result[] = array(
                        'id' => $item->gid,
                        'gname' => $item->gname
                    );
                }
                $this->result('', 0, $data_result, ['count' => $data['count']]);
                break;
        }
    }

    // 管理分组
    public function saveAction()
    {
        $gid = intval($this->request->getParam('gid'));
        if ($gid) {
            $group = AdminGroupsModel::find($gid);
            if (!$group) $this->ajaxresult(0, '未找到您要修改的信息');
            $this->view->assign('groupRight', explode(',', $group->rightlist));
            $this->view->assign('data', $group);
        }
        if ($this->request->isPost()) {
            $operation_before_data = array();
            $rights = $this->post('rights');
            $post_data = array(
                'gname' => $this->post('gname'),
                'rightlist' => join(',', array_unique($rights ? $rights : array()))
            );
            if ($group) {
                $operation_before_data = array(
                    'parent_id' => 0,
                    'gname' => $group->gname,
                    'rightlist' => $group->rightlist,
                );
                unset($post_data['gname']);
                $status = $group->save($post_data);
            } else {
                $group = new AdminGroupsModel();
                $status = $group->save($post_data);
            }

            if ($status == false) $this->ajaxresult(1, join($rights->getMessages(), '<br>'));
            $this->operation_log('编辑角色分组', $operation_before_data, $post_data);
            $this->ajaxresult(0, '处理成功');
        }
        // 加载所有权限资源
        $this->view->assign('allrights', AdminRightsModel::get_children_right(0, -4, false));
    }

    public function delAction()
    {
        $gid = intval($this->request->getParam('gid'));
        if ($gid && $gid != 1) {
            $group = AdminGroupsModel::find($gid);
            if ($group) {
                $group->delete();
                $this->operation_log('删除角色分组', array('gid' => $gid));
            }
        }
        $this->ajaxresult(0, '删除成功');
    }
}
